package com.abai.doubi.server.service.impl;

import com.abai.doubi.entity.pojo.Conversation;
import com.abai.doubi.entity.pojo.Role;
import com.abai.doubi.entity.pojo.RoleSkill;
import com.abai.doubi.server.service.IChatService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.util.List;

@Service
public class ChatServiceImpl implements IChatService {
    @Autowired
    private ChatClient chatClient;

    @Override
    public String generateReply(Role role, String userMessage, RoleSkill usedSkill, List<Conversation> historys) {
        String promptContent = buildSkillPrompt(role, userMessage, usedSkill);
        String message = userMessage + buildContextFromHistory(historys);
        String content = chatClient.prompt()
                .system(promptContent)
                .user(message)
                .call()
                .content();
        return content;
    }


    @Override
    public Flux<String> generateStreamReply(Role role, String userMessage,RoleSkill usedSkill, List<Conversation> historys) {
        String promptContent = buildSkillPrompt(role, userMessage, usedSkill);
        String message = userMessage + buildContextFromHistory(historys);
        Flux<String> content = chatClient.prompt()
                .system(promptContent)
                .user(message)
                .stream()
                .content();
        return content;
    }

    private String buildSkillPrompt(Role role,String userMessage, RoleSkill usedSkill) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("请将回答限制在200个字符以内。");
        if (usedSkill != null && usedSkill.getSkillTemplate() != null) {
            String template = usedSkill.getSkillTemplate();
            prompt.append(template
                    .replace("{skillName}", usedSkill.getSkillName())
                    .replace("{roleName}", role.getRoleName())
                    .replace("{topic}", userMessage));
        }
        return prompt.toString();
    }

    private String buildContextFromHistory(List<Conversation> historys) {
        if (historys == null || historys.isEmpty()) {
            return "";
        }
        StringBuilder context = new StringBuilder();
        context.append("最近对话历史：\n");
        for (Conversation conv : historys){
            context.append("用户: ").append(conv.getUserMessage()).append("\n");
            context.append("角色: ").append(conv.getRoleMessage()).append("\n");
        }
        return context.toString();
    }
}
